/**
 * SQL模板管理器 - UI交互模块
 * 负责模板渲染、模态框管理、表单处理等UI相关功能
 */

// 扩展TemplateManager类的UI功能
Object.assign(TemplateManager.prototype, {
    // 模板渲染
    renderTemplates() {
        this.templatesContainer.innerHTML = '';
        
        if (this.filteredTemplates.length === 0) {
            if (this.templates.length === 0) {
                this.showEmptyState();
            } else {
                this.showNoSearchResults();
            }
            return;
        }

        this.hideEmptyState();
        this.hideNoSearchResults();
        
        const grid = document.createElement('div');
        grid.className = 'grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6';
        
        this.filteredTemplates.forEach(template => {
            const card = this.createTemplateCard(template);
            grid.appendChild(card);
        });
        
        this.templatesContainer.appendChild(grid);
    },

    createTemplateCard(template) {
        const card = document.createElement('div');
        card.className = 'bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 hover:shadow-md transition-shadow cursor-pointer';
        
        // 计算参数数量
        let parameterCount = 0;
        let hasParameters = false;
        if (template.parameters && template.parameters !== '[]' && template.parameters !== '{}') {
            try {
                const params = JSON.parse(template.parameters);
                if (Array.isArray(params)) {
                    parameterCount = params.length;
                    hasParameters = parameterCount > 0;
                }
            } catch (e) {
                // 如果解析失败，仍然显示有参数但不显示数量
                hasParameters = true;
            }
        }
        
        const hasPlotly = template.plotly_code && template.plotly_code.trim();
        
        card.innerHTML = `
            <div class="p-6">
                <div class="flex justify-between items-start mb-3">
                    <h4 class="text-lg font-semibold text-gray-900 dark:text-white truncate flex-1 mr-2">${this.escapeHtml(template.id)}</h4>
                    <div class="flex space-x-2">
                        ${hasParameters ? `<span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200">${parameterCount > 0 ? `参数(${parameterCount})` : '参数'}</span>` : ''}
                        ${hasPlotly ? '<span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200">图表</span>' : ''}
                    </div>
                </div>
                <p class="text-gray-600 dark:text-gray-400 text-sm mb-4 line-clamp-3">${this.escapeHtml(template.description)}</p>
                <div class="bg-gray-50 dark:bg-gray-700 rounded-md p-3 mb-4">
                    <code class="text-xs text-gray-800 dark:text-gray-200 font-mono line-clamp-4">${this.escapeHtml(template.sql_template)}</code>
                </div>
                <div class="flex justify-between items-center">
                    <button class="view-btn text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300 text-sm font-medium" data-id="${template.id}">
                        查看详情
                    </button>
                    <div class="flex space-x-2">
                        <button class="edit-btn text-green-600 hover:text-green-800 dark:text-green-400 dark:hover:text-green-300 text-sm" data-id="${template.id}" title="编辑">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
                            </svg>
                        </button>
                        <button class="delete-btn text-red-600 hover:text-red-800 dark:text-red-400 dark:hover:text-red-300 text-sm" data-id="${template.id}" title="删除">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                            </svg>
                        </button>
                    </div>
                </div>
            </div>
        `;
        
        // 绑定事件
        card.querySelector('.view-btn').addEventListener('click', (e) => {
            e.stopPropagation();
            this.showTemplateDetails(template);
        });
        
        card.querySelector('.edit-btn').addEventListener('click', (e) => {
            e.stopPropagation();
            this.showEditTemplateModal(template);
        });
        
        card.querySelector('.delete-btn').addEventListener('click', (e) => {
            e.stopPropagation();
            this.showDeleteModal(template.id);
        });
        
        return card;
    },

    // 模态框管理
    showTemplateDetails(template) {
        this.modalTitle.textContent = `模板详情 - ${template.id}`;
        
        let parametersHtml = '';
        if (template.parameters && template.parameters !== '[]' && template.parameters !== '{}') {
            try {
                const params = JSON.parse(template.parameters);
                if (Array.isArray(params) && params.length > 0) {
                    parametersHtml = `
                        <div class="mb-6">
                            <h4 class="text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">参数配置</h4>
                            <div class="bg-gray-50 dark:bg-gray-700 rounded-lg p-4">
                                <div class="space-y-3">
                                    ${params.map(param => `
                                        <div class="border-l-4 border-blue-500 pl-4">
                                            <div class="flex items-center space-x-2 mb-1">
                                                <span class="font-medium text-gray-900 dark:text-white">${this.escapeHtml(param.name || 'N/A')}</span>
                                                <span class="px-2 py-1 bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200 text-xs rounded">${this.escapeHtml(param.type || 'string')}</span>
                                            </div>
                                            <p class="text-sm text-gray-600 dark:text-gray-400">${this.escapeHtml(param.description || '无描述')}</p>
                                        </div>
                                    `).join('')}
                                </div>
                            </div>
                        </div>
                    `;
                }
            } catch (e) {
                parametersHtml = `
                    <div class="mb-6">
                        <h4 class="text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">参数配置</h4>
                        <div class="bg-gray-50 dark:bg-gray-700 rounded-lg p-4">
                            <pre class="text-sm text-gray-800 dark:text-gray-200 font-mono">${this.escapeHtml(template.parameters)}</pre>
                        </div>
                    </div>
                `;
            }
        }
        
        let plotlyHtml = '';
        if (template.plotly_code && template.plotly_code.trim()) {
            plotlyHtml = `
                <div class="mb-6">
                    <h4 class="text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">Plotly可视化代码</h4>
                    <div class="bg-gray-50 dark:bg-gray-700 rounded-lg p-4">
                        <pre class="text-sm text-gray-800 dark:text-gray-200 font-mono overflow-x-auto">${this.escapeHtml(template.plotly_code)}</pre>
                    </div>
                </div>
            `;
        }
        
        this.modalContent.innerHTML = `
            <div class="space-y-6">
                <div>
                    <h4 class="text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">模板ID</h4>
                    <p class="text-gray-900 dark:text-white font-mono">${this.escapeHtml(template.id)}</p>
                </div>
                
                <div>
                    <h4 class="text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">描述</h4>
                    <p class="text-gray-900 dark:text-white">${this.escapeHtml(template.description)}</p>
                </div>
                
                <div>
                    <h4 class="text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">SQL模板</h4>
                    <div class="bg-gray-50 dark:bg-gray-700 rounded-lg p-4">
                        <pre class="text-sm text-gray-800 dark:text-gray-200 font-mono overflow-x-auto">${this.escapeHtml(template.sql_template)}</pre>
                    </div>
                </div>
                
                ${parametersHtml}
                ${plotlyHtml}
            </div>
        `;
        
        this.templateModal.classList.remove('hidden');
    },

    hideModal() {
        this.templateModal.classList.add('hidden');
    },

    showDeleteModal(templateId) {
        this.currentDeleteId = templateId;
        const template = this.templates.find(t => t.id === templateId);
        if (template) {
            this.deleteTemplateName.textContent = template.id;
            this.deleteModal.classList.remove('hidden');
        }
    },

    hideDeleteModal() {
        this.deleteModal.classList.add('hidden');
        this.currentDeleteId = null;
    },

    // 添加模板模态框
    showAddTemplateModal() {
        const addModal = document.getElementById('addTemplateModal');
        if (addModal) {
            addModal.classList.remove('hidden');
        }
    },

    // 编辑模板模态框
    showEditTemplateModal(template) {
        const editModal = document.getElementById('editTemplateModal');
        if (editModal) {
            // 填充表单数据
            document.getElementById('editTemplateId').value = template.id;
            document.getElementById('editTemplateDescription').value = template.description;
            document.getElementById('editTemplateSql').value = template.sql_template;
            document.getElementById('editTemplateParameters').value = template.parameters || '';
            document.getElementById('editTemplatePlotly').value = template.plotly_code || '';
            
            editModal.classList.remove('hidden');
        }
    },

    // 相似性搜索模态框
    showSimilarSearchModal() {
        const similarModal = document.getElementById('similarSearchModal');
        if (similarModal) {
            // 重置搜索表单
            document.getElementById('similarSearchInput').value = '';
            const resultsSection = document.getElementById('similarResults');
            if (resultsSection) {
                resultsSection.classList.add('hidden');
            }
            similarModal.classList.remove('hidden');
        }
    },

    // 模态框事件绑定
    bindModalEvents() {
        // 添加模板模态框事件
        const addModal = document.getElementById('addTemplateModal');
        const closeAddModalBtn = document.getElementById('closeAddModalBtn');
        const cancelAddBtn = document.getElementById('cancelAddBtn');
        const addTemplateForm = document.getElementById('addTemplateForm');
        
        if (closeAddModalBtn) {
            closeAddModalBtn.addEventListener('click', () => {
                addModal.classList.add('hidden');
            });
        }
        
        if (cancelAddBtn) {
            cancelAddBtn.addEventListener('click', () => {
                addModal.classList.add('hidden');
            });
        }
        
        if (addTemplateForm) {
            addTemplateForm.addEventListener('submit', (e) => this.handleAddTemplate(e));
        }
        
        // 编辑模板模态框事件
        const editModal = document.getElementById('editTemplateModal');
        const closeEditModalBtn = document.getElementById('closeEditModalBtn');
        const cancelEditBtn = document.getElementById('cancelEditBtn');
        const editTemplateForm = document.getElementById('editTemplateForm');
        
        if (closeEditModalBtn) {
            closeEditModalBtn.addEventListener('click', () => {
                editModal.classList.add('hidden');
            });
        }
        
        if (cancelEditBtn) {
            cancelEditBtn.addEventListener('click', () => {
                editModal.classList.add('hidden');
            });
        }
        
        if (editTemplateForm) {
            editTemplateForm.addEventListener('submit', (e) => this.handleEditTemplate(e));
        }
        
        // 相似性搜索模态框事件
        const similarModal = document.getElementById('similarSearchModal');
        const closeSimilarModalBtn = document.getElementById('closeSimilarModalBtn');
        const cancelSimilarBtn = document.getElementById('cancelSimilarBtn');
        const searchSimilarBtn = document.getElementById('searchSimilarBtn');
        
        if (closeSimilarModalBtn) {
            closeSimilarModalBtn.addEventListener('click', () => {
                similarModal.classList.add('hidden');
            });
        }
        
        if (cancelSimilarBtn) {
            cancelSimilarBtn.addEventListener('click', () => {
                similarModal.classList.add('hidden');
            });
        }
        
        if (searchSimilarBtn) {
            searchSimilarBtn.addEventListener('click', () => this.handleSimilarSearch());
        }
        
        // 点击模态框外部关闭
        if (addModal) {
            addModal.addEventListener('click', (e) => {
                if (e.target === addModal) addModal.classList.add('hidden');
            });
        }
        
        if (editModal) {
            editModal.addEventListener('click', (e) => {
                if (e.target === editModal) editModal.classList.add('hidden');
            });
        }
        
        if (similarModal) {
            similarModal.addEventListener('click', (e) => {
                if (e.target === similarModal) similarModal.classList.add('hidden');
            });
        }
    },

    // 表单处理
    async handleAddTemplate(e) {
        e.preventDefault();
        
        const formData = new FormData(e.target);
        
        // 处理参数字段，确保是有效的JSON数组
        let parameters = [];
        const parametersStr = formData.get('parameters');
        if (parametersStr && parametersStr.trim()) {
            try {
                parameters = JSON.parse(parametersStr);
                // 确保是数组格式
                if (!Array.isArray(parameters)) {
                    throw new Error('参数必须是数组格式');
                }
            } catch (error) {
                this.showError('参数格式错误，请输入有效的JSON数组格式');
                return;
            }
        }
        
        const templateData = {
            id: formData.get('id'),
            description: formData.get('description'),
            sql_template: formData.get('sql_template'),
            parameters: parameters,  // 直接传递JSON数组，不转换为字符串
            plotly_code: formData.get('plotly_code') || ''
        };
        
        try {
            const response = await authenticatedFetch('/api/v0/sql_templates', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(templateData)
            });
            
            const data = await response.json();
            if (data.type === 'success') {
                this.showSuccess('模板添加成功');
                document.getElementById('addTemplateModal').classList.add('hidden');
                e.target.reset();
                await this.loadTemplates();
            } else {
                throw new Error(data.error || '添加失败');
            }
        } catch (error) {
            console.error('添加模板失败:', error);
            this.showError('添加模板失败');
        }
    },

    async handleEditTemplate(e) {
        e.preventDefault();
        
        const formData = new FormData(e.target);
        
        // 处理参数字段，确保是有效的JSON数组
        let parameters = [];
        const parametersStr = formData.get('parameters');
        if (parametersStr && parametersStr.trim()) {
            try {
                parameters = JSON.parse(parametersStr);
                // 确保是数组格式
                if (!Array.isArray(parameters)) {
                    throw new Error('参数必须是数组格式');
                }
            } catch (error) {
                this.showError('参数格式错误，请输入有效的JSON数组格式');
                return;
            }
        }
        
        const templateData = {
            id: formData.get('id'),
            description: formData.get('description'),
            sql_template: formData.get('sql_template'),
            parameters: parameters,  // 直接传递JSON数组，不转换为字符串
            plotly_code: formData.get('plotly_code') || ''
        };
        
        try {
            const templateId = formData.get('id');
            const response = await authenticatedFetch(`/api/v0/sql_templates/${templateId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(templateData)
            });
            
            const data = await response.json();
            if (data.type === 'success') {
                this.showSuccess('模板更新成功');
                document.getElementById('editTemplateModal').classList.add('hidden');
                await this.loadTemplates();
            } else {
                throw new Error(data.error || '更新失败');
            }
        } catch (error) {
            console.error('更新模板失败:', error);
            this.showError('更新模板失败');
        }
    },

    async handleSimilarSearch() {
        const query = document.getElementById('similarSearchInput').value.trim();
        const resultsSection = document.getElementById('similarResults');
        const resultsContainer = document.getElementById('similarResultsContent');
        
        if (!query) {
            this.showError('请输入搜索内容');
            return;
        }
        
        try {
            // 显示结果区域和加载状态
            resultsSection.classList.remove('hidden');
            resultsContainer.innerHTML = '<div class="text-center py-4"><div class="animate-spin w-6 h-6 border-2 border-purple-500 border-t-transparent rounded-full mx-auto"></div><p class="text-gray-500 mt-2">搜索中...</p></div>';
            
            const response = await authenticatedFetch('/api/v0/similar_sql_templates', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ query })
            });
            
            const data = await response.json();
            if (data.type === 'df' && data.df.length > 0) {
                this.renderSimilarResults(data.df);
            } else {
                resultsContainer.innerHTML = '<div class="text-center py-8"><p class="text-gray-500">未找到相似的模板</p></div>';
            }
        } catch (error) {
            console.error('相似性搜索失败:', error);
            resultsContainer.innerHTML = '<div class="text-center py-8"><p class="text-red-500">搜索失败，请重试</p></div>';
        }
    },

    renderSimilarResults(results) {
        const resultsContainer = document.getElementById('similarResultsContent');
        resultsContainer.innerHTML = results.map(template => `
            <div class="border border-gray-200 dark:border-gray-600 rounded-lg p-4 hover:bg-gray-50 dark:hover:bg-gray-700 cursor-pointer" onclick="templateManager.showTemplateDetails(${JSON.stringify(template).replace(/"/g, '&quot;')})">
                <div class="flex justify-between items-start mb-2">
                    <h4 class="font-medium text-gray-900 dark:text-white">${this.escapeHtml(template.id)}</h4>
                    <span class="text-xs text-gray-500 bg-gray-100 dark:bg-gray-600 px-2 py-1 rounded">相似度: ${Math.round((template.similarity || 0) * 100)}%</span>
                </div>
                <p class="text-sm text-gray-600 dark:text-gray-400 mb-2">${this.escapeHtml(template.description)}</p>
                <div class="bg-gray-100 dark:bg-gray-600 rounded p-2">
                    <code class="text-xs text-gray-800 dark:text-gray-200">${this.escapeHtml(template.sql_template.substring(0, 100))}${template.sql_template.length > 100 ? '...' : ''}</code>
                </div>
            </div>
        `).join('');
    },

    // 工具方法
    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
});